<template>
  <el-drawer v-model="visibleDrawer" :destroy-on-close="true" :with-header="false" size="50%">
    <el-form :model="formModel" ref="formRef">
      <el-form-item label="题目标题:">
        <el-input style="width:387px !important" v-model="formQuestion.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="题目难度:">
        <QuestionSelector style="width:387px !important" v-model="formQuestion.difficulty" width="100%"
          placeholder="请选择题目难度">
        </QuestionSelector>
      </el-form-item>
      <el-form-item label="时间限制（单位毫秒）:">
        <el-input style="width:300px !important" v-model="formQuestion.timeLimit" placeholder="请输入时间限制"></el-input>
      </el-form-item>
      <el-form-item label="空间限制（单位字节）:">
        <el-input style="width:300px !important" v-model="formQuestion.spaceLimit" placeholder="请输入空间限制"></el-input>
      </el-form-item>
      <el-form-item label="题目内容:">
        <div class="editor">
          <quill-editor placeholder="请输入题目内容" v-model:content="formQuestion.content" content-type="html"></quill-editor>
        </div>
      </el-form-item>
      <el-form-item label="题目用例:">
        <el-input style="width:387px !important" v-model="formQuestion.questionCase" placeholder="请输入题目用例"></el-input>
      </el-form-item>
      <el-form-item label="编程语言:">
        <el-select v-model="formQuestion.language" style="width:387px !important" placeholder="请选择编程语言">
          <el-option label="Java" value="java" />
          <el-option label="Python" value="python" />
        </el-select>
      </el-form-item>
      <el-form-item label="默认代码块:">
        <code-editor @update:value="handleEditorContent" ref="defaultCodeRef" :language="formQuestion.language"></code-editor>
      </el-form-item>
      <el-form-item label="main函数:">
        <code-editor @update:value="handleEditorMainFunc" ref="mainFucRef" :language="formQuestion.language"></code-editor>
      </el-form-item>
      <el-form-item>
        <el-button class="question-button" type="primary" plain @click="onSubmit()">发布</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script setup>
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import CodeEditor from './CodeEditor.vue'
import QuestionSelector from './QuestionSelector.vue'
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { addQuestionService, getQuestionDetailService, editQuestionService } from '@/apis/question'

const visibleDrawer = ref(false)
const formQuestion = reactive({
  questionId: '',
  title: '',
  difficulty: '',
  content: '',
  questionCase: '',
  timeLimit: '',
  spaceLimit: '',
  language: 'java',
  defaultCode: '',
  mainFuc: '',
  // 存储不同语言的代码
  javaDefaultCode: '',
  javaMainFunc: '',
  pythonDefaultCode: '',
  pythonMainFunc: ''
})

const defaultCodeRef = ref()
const mainFucRef = ref()

// 监听语言变化
watch(() => formQuestion.language, (newLanguage, oldLanguage) => {
  if (!newLanguage || newLanguage === oldLanguage) return

  // 先保存当前编辑器的内容到对应语言的变量中
  if (defaultCodeRef.value && mainFucRef.value) {
    const currentDefaultCode = defaultCodeRef.value.getAceCode() || ''
    const currentMainFunc = mainFucRef.value.getAceCode() || ''
    
    // 保存旧语言的代码
    if (oldLanguage === 'java') {
      formQuestion.javaDefaultCode = currentDefaultCode
      formQuestion.javaMainFunc = currentMainFunc
    } else if (oldLanguage === 'python') {
      formQuestion.pythonDefaultCode = currentDefaultCode
      formQuestion.pythonMainFunc = currentMainFunc
    }

    // 加载新语言的代码
    let newDefaultCode = ''
    let newMainFunc = ''
    if (newLanguage === 'java') {
      newDefaultCode = formQuestion.javaDefaultCode || ''
      newMainFunc = formQuestion.javaMainFunc || ''
    } else if (newLanguage === 'python') {
      newDefaultCode = formQuestion.pythonDefaultCode || ''
      newMainFunc = formQuestion.pythonMainFunc || ''
    }

    // 更新表单的当前代码
    formQuestion.defaultCode = newDefaultCode
    formQuestion.mainFuc = newMainFunc

    // 更新编辑器内容
    nextTick(() => {
      defaultCodeRef.value.setAceCode(newDefaultCode)
      mainFucRef.value.setAceCode(newMainFunc)
    })
  }
})

// 更新打开抽屉的方法
async function open(questionId) {
  visibleDrawer.value = true
  
  if (questionId) {
    // 从服务器获取题目数据
    const { data } = await getQuestionDetailService(questionId)
    
    // 更新表单数据，保留已有的代码
    Object.assign(formQuestion, {
      ...data,
      // 如果服务器返回了代码，使用服务器的代码，否则保留当前的代码
      javaDefaultCode: data.javaDefaultCode || formQuestion.javaDefaultCode,
      javaMainFunc: data.javaMainFunc || formQuestion.javaMainFunc,
      pythonDefaultCode: data.pythonDefaultCode || formQuestion.pythonDefaultCode,
      pythonMainFunc: data.pythonMainFunc || formQuestion.pythonMainFunc
    })
    
    // 根据当前语言设置编辑器显示的内容
    if (formQuestion.language === 'java') {
      formQuestion.defaultCode = formQuestion.javaDefaultCode
      formQuestion.mainFuc = formQuestion.javaMainFunc
    } else if (formQuestion.language === 'python') {
      formQuestion.defaultCode = formQuestion.pythonDefaultCode
      formQuestion.mainFuc = formQuestion.pythonMainFunc
    }
    
    // 更新编辑器内容
    nextTick(() => {
      if (defaultCodeRef.value && mainFucRef.value) {
        defaultCodeRef.value.setAceCode(formQuestion.defaultCode || '')
        mainFucRef.value.setAceCode(formQuestion.mainFuc || '')
      }
    })
  }
}

defineExpose({
  open
})

function validate() {
  let msg = ''
  if (!formQuestion.title) {
    msg = '请添加题目标题'
  } else if (formQuestion.difficulty == '') {
    msg = '请选择题目难度'
  } else if (!formQuestion.timeLimit) {
    msg = '请输入时间限制'
  } else if (!formQuestion.spaceLimit) {
    msg = '请输入空间限制'
  } else if (!formQuestion.content) {
    msg = '请输入题目内容信息'
  } else if (!formQuestion.questionCase) {
    msg = '请输入题目用例名称'
  } else if (!formQuestion.defaultCode) {
    msg = '请输入默认代码'
  } else if (!formQuestion.language) {
    msg = '请选择编程语言'
  } else if (!formQuestion.mainFuc) {
    msg = '请输入main函数'
  } else {
    msg = ''
  }
  return msg
}

const emit = defineEmits(['success'])

async function onSubmit() {
  const errorMessage = validate()
  if (errorMessage) {
    ElMessage.error(errorMessage)
    return false
  }

  // 保存当前编辑器的内容到当前语言的变量中
  const currentDefaultCode = defaultCodeRef.value?.getAceCode() || ''
  const currentMainFunc = mainFucRef.value?.getAceCode() || ''
  
  // 准备提交的数据
  const submitData = {
    ...formQuestion,
    defaultCode: currentDefaultCode,  // 当前编辑器的代码
    mainFuc: currentMainFunc,        // 当前编辑器的main函数
    javaDefaultCode: formQuestion.language === 'java' ? currentDefaultCode : formQuestion.javaDefaultCode,
    javaMainFunc: formQuestion.language === 'java' ? currentMainFunc : formQuestion.javaMainFunc,
    pythonDefaultCode: formQuestion.language === 'python' ? currentDefaultCode : formQuestion.pythonDefaultCode,
    pythonMainFunc: formQuestion.language === 'python' ? currentMainFunc : formQuestion.pythonMainFunc
  }
  
  const fd = new FormData()
  for (let key in submitData) {
    // 确保即使是空字符串也会被提交
    fd.append(key, submitData[key] || '')
  }
  
  try {
    if (formQuestion.questionId) {
      //编辑题目请求
      await editQuestionService(fd)
      ElMessage.success('编辑成功')
      emit('success', 'edit')
    } else {
      await addQuestionService(fd)
      ElMessage.success('添加成功')
      emit('success', 'add')
    }
    visibleDrawer.value = false
  } catch (error) {
    ElMessage.error('保存失败，请重试')
    console.error('保存失败:', error)
  }
}

function handleEditorContent(content) {
  formQuestion.defaultCode = content
  
  // 同时更新对应语言的代码
  if (formQuestion.language === 'java') {
    formQuestion.javaDefaultCode = content
  } else if (formQuestion.language === 'python') {
    formQuestion.pythonDefaultCode = content
  }
}

function handleEditorMainFunc(content) {
  formQuestion.mainFuc = content
  
  // 同时更新对应语言的代码
  if (formQuestion.language === 'java') {
    formQuestion.javaMainFunc = content
  } else if (formQuestion.language === 'python') {
    formQuestion.pythonMainFunc = content
  }
}
</script>

<style lang="scss">
.question-button {
  width: 200px;
}
</style>